#include "stdint.h"

#include "alarm_data_mutex.h"

void insert_alarm(alarm_t* p_alarm)
{
	alarm_t** prior;
	alarm_t* next;
	int signal_ret_val;

	prior = &alarm_list;
	next = *prior;
	while(next != NULL) {
		if(p_alarm->time <= next->time) {
			p_alarm->next = next;
			*prior = p_alarm;
			break;
		}
		next = next->next;
		prior =&((*prior)->next);
	}
	if(next == NULL) {
		*prior = p_alarm;
		p_alarm->next = NULL;
	}

#ifdef DEBUG
		//print alarm list
		next = alarm_list;
		int16_t count = 0;
		printf("The current alarm list is:\n");
		while(next != NULL) {
			count++;
			printf("%d seconds:%d message:%s\n", count, next->seconds, next->message);
			next = next->next;
		}
		printf("\n");
#endif

	if(0 == current_time || p_alarm->time < current_time) {
		current_time = p_alarm->time;
		signal_ret_val = pthread_cond_signal(&alarm_cond);
		if(0 != signal_ret_val) {
			printf("&insert_alarm: fail to send singal!"
					" program exit!\n");
			exit(0);
		}
	}

	return;
}
